package com.yby6.web.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import com.yby6.common.constant.Constants;
import com.yby6.common.core.domain.SysMenu;
import com.yby6.common.core.redis.RedisUtils;
import com.yby6.common.satoken.LoginHelper;
import com.yby6.common.utils.ServletUtils;
import com.yby6.framework.satoken.properties.SaTokenProperties;
import com.yby6.system.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class WebConfiguration implements WebMvcConfigurer {
    private final SaTokenProperties saTokenProperties;

    private final SysMenuService sysMenuService;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<SysMenu> permissions = RedisUtils.getCacheList(Constants.MENU_KEY);
        // 拦截所有URL请求
        registry.addInterceptor(new SaInterceptor(handler -> {
            log.info("拦截请求:{}", ServletUtils.getRequest().getRequestURI());
            SaRouter.match("/**", r -> StpUtil.checkLogin());
//            List<String> list = StpUtil.getPermissionList();
            log.info("当前请求人信息:{}", LoginHelper.getSysUser());

            // 路由权限
//            for (SysMenu permission : permissions) {
//                // 匹配请求方式
//                SaRouter
//                        // 匹配请求地址
//                        .match(true)
//                        // 校验权限
//                        .check(r -> checkPermission(list,permission.getPermission()));
//            }
        })).addPathPatterns("/**").excludePathPatterns(saTokenProperties.getAnonUrls());
    }

    /**
     * 自定义校验当前登陆的权限标识是否存在
     * @return
     */
    private boolean checkPermission(List<String> list, String permission) {
        // 空集合直接返回false
        if (list == null || list.size() == 0) {
            return false;
        }

        // 先尝试一下简单匹配，如果可以匹配成功则无需继续模糊匹配
        if (list.contains(permission)) {
            return true;
        }

        // 开始模糊匹配
        for (String patt : list) {
            if (SaFoxUtil.vagueMatch(patt, permission)) {
                return true;
            }
        }

        // 走出for循环说明没有一个元素可以匹配成功
        return false;
    }
}
